package solution7;

public class Solution {
    public int reverse(int x) {
        long res = 0;
        while (x != 0) {
            int tail = x % 10;
            x = x / 10;
            res  = res * 10 + tail;
            if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) {
                return 0;
            }
        }
        return  (int)res;
    }

    //If overflow exists, the new result will not equal previous one.
    public int reverse2(int x)
    {
        int result = 0;

        while (x != 0)
        {
            int tail = x % 10;
            int newResult = result * 10 + tail;
            if ((newResult - tail) / 10 != result)
            { return 0; }
            result = newResult;
            x = x / 10;
        }

        return result;
    }
}
